-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.c
More file actions
59 lines (49 loc) · 1.35 KB
/
Solution.c
File metadata and controls
59 lines (49 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <stdlib.h>
int detectCycleUtil(int v, int visited[], int recStack[], int graph[][100], int vertices) {
visited[v] = 1;
recStack[v] = 1;
for (int i = 0; i < vertices; i++) {
if (graph[v][i]) {
if (!visited[i] && detectCycleUtil(i, visited, recStack, graph, vertices)) {
return 1;
} else if (recStack[i]) {
return 1;
}
}
}
recStack[v] = 0;
return 0;
}
int detectCycle(int graph[][100], int vertices) {
int visited[vertices];
int recStack[vertices];
for (int i = 0; i < vertices; i++) {
visited[i] = 0;
recStack[i] = 0;
}
for (int i = 0; i < vertices; i++) {
if (!visited[i] && detectCycleUtil(i, visited, recStack, graph, vertices)) {
return 1;
}
}
return 0;
}
int main() {
int vertices, edges;
printf("Enter the number of vertices and edges: ");
scanf("%d %d", &vertices, &edges);
int graph[100][100] = {0};
printf("Enter the edges (u -> v):\n");
for (int i = 0; i < edges; i++) {
int u, v;
scanf("%d %d", &u, &v);
graph[u][v] = 1;
}
if (detectCycle(graph, vertices)) {
printf("Cycle detected in the graph.\n");
} else {
printf("No cycle detected in the graph.\n");
}
return 0;
}